package com.swt.testdemo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swt.testdemo.config.ResponseBean;
import com.swt.testdemo.config.ResponseMessage;
import com.swt.testdemo.dao.SysDataSourceDao;
import com.swt.testdemo.dao.SysDataTemplateDao;
import com.swt.testdemo.dao.SysOntologyDao;
import com.swt.testdemo.entity.SysDataSourceEntity;
import com.swt.testdemo.entity.SysDataTemplateEntity;
import com.swt.testdemo.entity.SysOntologyEntity;
import com.swt.testdemo.exception.AgyException;
import com.swt.testdemo.form.CreateDataTemplateForm;
import com.swt.testdemo.form.EditDataTemplateForm;
import com.swt.testdemo.form.QueryDataSourceForm;
import com.swt.testdemo.form.QueryDataTemplateForm;
import com.swt.testdemo.service.SysDataTemplateService;
import com.swt.testdemo.util.AgyExcelUtil;
import com.swt.testdemo.util.RedisUtil;
import com.swt.testdemo.util.ValidatorUtil;
import com.swt.testdemo.vo.SysDataTemplateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author BleethNie
 * @version 1.0
 * @date 2020/11/12 17:33
 **/
@Service("SysDataTemplateService")
public class SysDataTemplateServiceImpl extends ServiceImpl<SysDataTemplateDao, SysDataTemplateEntity> implements SysDataTemplateService {

    @Autowired
    private SysDataTemplateDao sysDataTemplateDao;

    @Autowired
    private SysOntologyDao sysOntologyDao;

    @Autowired
    private SysDataSourceDao sysDataSourceDao;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public ResponseBean listDataTemplate(QueryDataTemplateForm form) {
        String templateNameFilter = form.getTemplateNameFilter();
        List<SysDataTemplateEntity> templateList = sysDataTemplateDao.queryDataTemplate(templateNameFilter);

        //ontology查询
        List<SysOntologyEntity> ontologyList = sysOntologyDao.selectAllOntology();
        Map<Integer, SysOntologyEntity> mapOntologyMap = new HashMap<>();
        for (SysOntologyEntity sysOntologyEntity : ontologyList) {
            Integer id = sysOntologyEntity.getId();
            mapOntologyMap.put(id, sysOntologyEntity);
        }

        //返回结构体
        List<SysDataTemplateVO> templateVOList = new ArrayList<>();

        for (SysOntologyEntity sysOntologyEntity : ontologyList) {
            Integer ontoId = sysOntologyEntity.getId();
            SysDataTemplateVO sysDataTemplateVO = new SysDataTemplateVO();
            sysDataTemplateVO.setOntologyId(ontoId);
            sysDataTemplateVO.setOntologyName(sysOntologyEntity.getOntologyName());
            List<SysDataTemplateEntity> tempList = new ArrayList<>();
            sysDataTemplateVO.setTemplateList(tempList);
            templateVOList.add(sysDataTemplateVO);

            for (int i = 0; i < templateList.size(); i++) {
                SysDataTemplateEntity sysDataTemplateEntity = templateList.get(i);
                Integer ontologyId = sysDataTemplateEntity.getOntologyId();
                if (ontoId.equals(ontologyId)) {
                    tempList.add(sysDataTemplateEntity);
                }
            }
        }

        return new ResponseBean(200,"查询成功",templateVOList);
    }

    @Override
    public ResponseBean getDataTemplateInfo(Integer dataTemplateId) {


        return null;
    }

    @Override
    public ResponseMessage downloadDataTemplate(HttpServletRequest request, HttpServletResponse response, Integer dataTemplateId) {
        SysDataTemplateEntity sysDataTemplateEntity = this.getById(dataTemplateId);
        if (sysDataTemplateEntity == null){
            return new ResponseMessage(500,"下载失败，请检查需要下载的模板是否存在");
        }
        String templateType = sysDataTemplateEntity.getTemplateType();
        if (SysDataTemplateEntity.TEMPLATE_TYPE_UNSORT.equals(templateType)){
            return new ResponseMessage(500,"系统内置模板，无法下载");
        }
        String templateContent = sysDataTemplateEntity.getTemplateContent();
        Integer ontologyId = sysDataTemplateEntity.getOntologyId();
        String templateName = sysDataTemplateEntity.getTemplateName();
        SysOntologyEntity sysOntologyEntity = sysOntologyDao.selectById(ontologyId);
        if (sysOntologyEntity == null){
           return new ResponseMessage(500,"数据模板内容错误。数据模板指定的ontology不存在");
        }
        String ontologyName = sysOntologyEntity.getOntologyName();

        if (StrUtil.isEmpty(templateContent)){
            return new ResponseMessage(500,"当前模板内容不全，无法导出");
        }

        if (!JSONUtil.isJson(templateContent)){
            return new ResponseMessage(500,"模板内容不合法，请重新配置后再下载");
        }

        List<String> dataFiledList = new ArrayList<>();

        //解析json内容
        JSONObject root = new JSONObject(templateContent);

        JSONArray node = root.getJSONArray("node");

        for (Object o : node) {
            JSONObject nodeObject = (JSONObject) o;
            JSONArray attributeArray = nodeObject.getJSONArray("attribute");
            for (Object attribute : attributeArray) {
                JSONObject attributeJsonObject = (JSONObject) attribute;
                String dataAttribute = attributeJsonObject.getStr("dataAttribute");
                dataFiledList.add(dataAttribute);

            }
        }
        DateTime current = DateUtil.date();
        String dateStr = DateUtil.format(current, "yyyyMMddHHmmss");

        String downloadTemplateName =ontologyName+"_"+templateName+"_"+dateStr+".xlsx";

        //写出到excel
        AgyExcelUtil.httpWrite(response,downloadTemplateName,dataFiledList,null);


        return new ResponseMessage(200,"下载成功");
    }

    @Override
    public ResponseBean createDataTemplate(@RequestBody CreateDataTemplateForm form) {

        DateTime current = DateUtil.date();

        Integer ontologyId = form.getOntologyId();

        JSONObject templateContent = form.getTemplateContent();
        String templateName = form.getTemplateName();
        SysDataTemplateEntity entity = new SysDataTemplateEntity();
        entity.setTemplateContent(templateContent.toStringPretty());
        entity.setUpdateTime(current);
        entity.setCreatedTime(current);
        entity.setTemplateType(SysDataTemplateEntity.TEMPLATE_TYPE_SORT);
        entity.setTemplateName(templateName);
        entity.setOntologyId(ontologyId);
        boolean success = this.save(entity);

        if (!success){
            throw new AgyException("创建模板失败，请检查参数是否正确");
        }
        Integer dataSourceId = form.getDataSourceId();
        if (dataSourceId !=null){
            SysDataSourceEntity sysDataSourceEntity = sysDataSourceDao.selectById(dataSourceId);
            if (sysDataSourceEntity !=null){
                Integer templateId = entity.getId();
                sysDataSourceEntity.setDataTemplateId(templateId);
                sysDataSourceDao.updateById(sysDataSourceEntity);
            }
        }



        return new ResponseBean(200,"创建成功",entity);
    }

    @Override
    public ResponseBean editDataTemplate(EditDataTemplateForm form) {
       String key ="data:template:"+form.getId();
       redisUtil.del(key);

        Integer templateFormId = form.getId();
        Integer ontologyId = form.getOntologyId();
        String templateName = form.getTemplateName();
        JSONObject templateContent = form.getTemplateContent();

        //判断
        SysDataTemplateEntity sysDataTemplateEntity = this.getById(templateFormId);
        if (sysDataTemplateEntity == null){
           throw new AgyException("参数异常，无法通过id查询dao");
        }
        String templateType = sysDataTemplateEntity.getTemplateType();
        if (SysDataTemplateEntity.TEMPLATE_TYPE_UNSORT.equals(templateType)){
            throw new AgyException("系统内置模板，无法编辑");
        }
        if (StrUtil.isNotEmpty(templateName)){
            sysDataTemplateEntity.setTemplateName(templateName);
        }
         sysDataTemplateEntity.setOntologyId(ontologyId);
         sysDataTemplateEntity.setTemplateContent(templateContent.toStringPretty());



        //更新数据
        this.updateById(sysDataTemplateEntity);


        return new ResponseBean(200,"编辑数据模板成功",sysDataTemplateEntity);
    }

    @Override
    public ResponseMessage deleteDataTemplate(Integer dataTemplateId) {
        String key = "data:template:"+dataTemplateId;
        redisUtil.del(key);

        //判断要删除的数据模板是否存在
        SysDataTemplateEntity sysDataTemplateEntity = this.getById(dataTemplateId);
        if (sysDataTemplateEntity==null){
            return new ResponseMessage(500,"删除失败，请检查需要删除的模板是否存在");
        }
        String templateType = sysDataTemplateEntity.getTemplateType();
        if (SysDataTemplateEntity.TEMPLATE_TYPE_UNSORT.equals(templateType)){
              return new ResponseMessage(500,"系统内置模板，无法删除");
        }

        boolean success = this.removeById(dataTemplateId);


        return new ResponseMessage(200,"删除成功");
    }

    @Override
    public ResponseBean getDataSourceList(QueryDataSourceForm form) {
        //参数校验
        ValidatorUtil.validateEntity(form);

        String classificationFilter = form.getClassificationFilter();
        Integer limit = form.getLimit();
        Integer page = form.getPage();

        return null;
    }


}
